package com.leff.cards.entity;

import java.util.ArrayList;

import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;

public abstract class EntityWrapper {

	protected static final String ID = "id";
	
	private Entity mEntity;
	
	public EntityWrapper(Entity E) {
		mEntity = E;
	}
	public EntityWrapper(String kind) {
		mEntity = new Entity(kind);
	}
	
	public final Entity getEntity() {
		return mEntity;
	}
	
	public final void put(String key, Object value) {
		mEntity.setProperty(key, value);
	}
	public final void embed(String key, EntityWrapper E) {
		EmbeddedEntity emb = new EmbeddedEntity();
		emb.setKey(E.getKey());
		emb.setPropertiesFrom(E.getEntity());
		
		put(key, emb);
	}
	public final void embedList(String key, ArrayList<? extends EntityWrapper> objs) {
		
		ArrayList<EmbeddedEntity> embs = new ArrayList<EmbeddedEntity>();
		for(EntityWrapper E : objs) {
			embs.add(E.toEmbeddedEntity());
		}
		
		put(key, embs);
	}
	
	public final Object get(String key) {
		return mEntity.getProperty(key);
	}
	public final Entity extract(String key) {
		EmbeddedEntity emb = (EmbeddedEntity)mEntity.getProperty(key);
		if(emb == null) {
			return null;
		}
		Entity E = new Entity(emb.getKey());
		E.setPropertiesFrom(emb);
		return E;
	}
	@SuppressWarnings("unchecked")
	public final ArrayList<Entity> extractList(String key) {
		
		ArrayList<EmbeddedEntity> embs = (ArrayList<EmbeddedEntity>)get(key);
		ArrayList<Entity> entities = new ArrayList<Entity>();
		
		if(embs == null || embs.size() == 0) {
			return entities;
		}
		
		for(EmbeddedEntity emb : embs) {
			Entity E = new Entity(emb.getKey());
			E.setPropertiesFrom(emb);
			entities.add(E);
		}
		
		return entities;
	}
	
	private EmbeddedEntity toEmbeddedEntity() {
		
		EmbeddedEntity emb = new EmbeddedEntity();
		emb.setKey(mEntity.getKey());
		emb.setPropertiesFrom(mEntity);
		
		return emb;
	}
	public final Key getKey() {
		return mEntity.getKey();
	}
	public final long getId() {
		return mEntity.getKey().getId();
	}
	public final String getKeyName() {
		return mEntity.getKey().getName();
	}
	
	public abstract Object toJSON();
//	protected String toJSONString() { return "You shouldn't be using this function"; }
	
	@Override
	public final boolean equals(Object other) {
		if(!(other instanceof EntityWrapper)) {
			return false;
		}
		EntityWrapper O = (EntityWrapper)other;
		return mEntity.equals(O.getEntity());
	}
}
